#!groovy

@Library('ops-share-librarya@master') _

def nexus = new org.devops.nexus()
def sonarq = new org.devops.sonarq()
def dingtalk = new org.devops.dingtalk()
def mysql = new org.devops.mysql()
String robotId = "BuildBoy"
String GIT_REPO_URL_String = 'git@gitee.com:wolfan_119/spring-boot-3-hello-world-jdk21.git'

def job_msg_map = mysql.get_mysql_msg_map('jenkins','HelloWorld-SqlPipeline')
env.GIT_REPO_URL_MAP = job_msg_map.git_repo_url

def get_mysql_msg = mysql.get_mysql_msg("HelloWorld-SqlPipeline")
job_msg = mysql.get_job_msg(get_mysql_msg)
env.GIT_REPO_URL_DB = job_msg.git_repo_url

//def urls = job_msg_map.git_repo_url // 直接访问 run_node 字段
//def resultList = mysql.get_mysql_msg_list('jenkins','HelloWorld-SqlPipeline')
//env.GIT_REPO_URL_LIST = resultList[2]


pipeline {
    agent { node { label "node47"}}
    tools {
        git 'Git'
        maven 'maven399'
        jdk 'jdk2102'
    } 
    environment {
        GIT_REPO_URL = 'git@gitee.com:wolfan_119/spring-boot-3-hello-world-jdk21.git'
        REGISTRY_URL = 'harbor.muscledog.top'
        HARBOR_URL = 'https://harbor.muscledog.top'
        PROJECT_GROUP = 'devops'
        PROJECT_NAME = 'hello-world-jdk21'
        CONTAINER_NAME = 'hello-world-jdk21'
        OPS_SHARE_LIBRARY = 'git@gitee.com:wolfan_119/ops-share-librarya.git'
        REPOSITORY = 'DevopsArtifact'
    }
    options {
        timeout(time: 10, unit: 'MINUTES')
        disableConcurrentBuilds()
        timestamps()
    }
    parameters {
        gitParameter(
            name: 'BRANCH_TAG',
            type: 'PT_BRANCH_TAG',
            defaultValue: 'master',
            description: '请选择你要部署的分支或Tag',
            useRepository: GIT_REPO_URL_String, // 这里要使用完整的Git仓库地址
            quickFilterEnabled: true // 启用快速筛选
        )
        booleanParam(defaultValue: false, description: '是否进行项目回滚?', name: 'ROLLBACK_TAG')
    }
    stages {
        stage('获取数据') {
            steps {
                script {
                    // 调用 get_mysql_msg 方法
                    //def resultList = mysql.get_mysql_msg_list('jenkins','HelloWorld-SqlPipeline')
                    // 打印结果 List
                    //println "Result List: ${resultList}"
                    //println "${env.GIT_REPO_URL_LIST}"
                    println "GIT_REPO_URL_MAP: ${GIT_REPO_URL_MAP}"
                    println "GIT_REPO_URL_DB: ${GIT_REPO_URL_DB}"
                }
            }
        }    
        stage('Example') {
            steps {
                script {
                    PrintMes("Generated version: green", 'green')
                    //def version = createVersion()
                    //PrintMes("Generated version: ${version}", 'red')
                }
            }
        }
        stage('Check requirement') {
            steps {
                script {
                    // 判断条件
                    if (params.ROLLBACK_TAG && env.BRANCH_TAG.startsWith('rel-')) {
                        echo "条件满足：ROLLBACK_TAG 为真，且 BRANCH_TAG 以 rel- 开头，继续执行后续步骤。"
                        // 在这里添加继续执行的逻辑
                    } else if (!params.ROLLBACK_TAG && !env.BRANCH_TAG.startsWith('rel-')) {
                        echo "条件满足：ROLLBACK_TAG 为假，且BRANCH_TAG 不以 rel- 开头，继续执行后续步骤。"
                        // 在这里添加继续执行的逻辑
                    } else {
                        echo "条件不满足，终止整个流程。"
                        // 使用 error 函数终止构建
                        error("构建中止：条件不满足。")
                    }
                }
            }
        }
        stage('CleanWorkDir') {
            steps {
                cleanWs()
            }
        }
        stage('Checkout') {
            steps {
                script {
                echo "Using repository: ${env.GIT_REPO_URL}"
                checkout([$class: 'GitSCM', 
                        branches: [[name: params.BRANCH_TAG]], 
                        userRemoteConfigs: [[url: "${GIT_REPO_URL}", credentialsId: "GiteeKey"]]]
                        )
                def PULL_TIME = sh(script: "echo `date +'%Y-%m-%d %H:%M:%S'`", returnStdout: true).trim() // 构建开始时间
                def COMMIT_ID = sh(script: 'git log -1 --pretty=format:%h',  returnStdout: true).trim() // 代码COMMIT_ID
                def TRACE_ID = sh(script: "echo `head -c 32 /dev/random | base64`",  returnStdout: true).trim() // 随机生成TRACE_ID
                def COMMIT_USER = sh(script: 'git log -1 --pretty=format:%an', returnStdout: true).trim() // 代码最后提交者
                def COMMIT_TIME = sh(script: 'git log -1 --pretty=format:%ai', returnStdout: true).trim() // 提交最后时间
                def COMMIT_INFO = sh(script: 'git log -1 --pretty=format:%s',  returnStdout: true).trim() // 提交最后信息
                PrintMes("Commit User: ${COMMIT_USER}", 'purple')
                PrintMes("Commit Time: ${COMMIT_TIME}", 'purple')
                PrintMes("Commit Info: ${COMMIT_INFO}", 'purple')

                if (params.ROLLBACK_TAG) {
                    wrap([$class: 'BuildUser']) {
                        echo "Built by: ${env.BUILD_USER_ID}"
                        currentBuild.description = 
                            "流水线执行者: ${env.BUILD_USER_ID}\n" +
                            "项目回滚ID: ${env.BRANCH_TAG}\n" +
                            "tag: '项目回滚'"
                        }
                } else {
                    env._tag = createVersion()
                    wrap([$class: 'BuildUser']) {
                        echo "Built by: ${env.BUILD_USER_ID}"
                        currentBuild.description = 
                            "流水线执行者: ${env.BUILD_USER_ID}\n" +
                            "分支: ${env.BRANCH_TAG}\n" +
                            "tag: ${_tag}\n" +
                            "代码提交者: ${COMMIT_USER}\n" +
                            "构建开始时间: ${PULL_TIME}\n" +
                            "提交时间: ${COMMIT_TIME}\n" +
                            "提交信息: ${COMMIT_INFO}"
                        }
                    }
                }
            }
        }
        stage('Build') {
            when {
                expression { 
                    return !params.BRANCH_TAG.startsWith('rel-')
                }
            }
            steps {
                PrintMes("项目开始构建", 'green')
                sh 'mvn clean package -Dmaven.test.skip=true'
                sh 'tar zcf ${PROJECT_NAME}.tar.gz target/spring-boot-3-hello-world-1.0.0-SNAPSHOT.jar'
            }
        }
        stage('Upload to Nexus') {
            when {
                expression { 
                    return !params.BRANCH_TAG.startsWith('rel-')
                }
            }
            steps {
                script {
                    PrintMes("Upload to Nexus", 'green')
                    echo "Uploading ${PROJECT_NAME} to ${REPOSITORY} with tag ${_tag}"
                    //传入参数的时候不要带有${}，直接使用变量名即可，否则报错
                    nexus.NexusUploadTargz(PROJECT_NAME,REPOSITORY,_tag)
                }
            }
        }
        stage("SonarQube Analysis") {
            when {
                expression { 
                    // 检查 BRANCH_TAG 是否不以 'rel-' 开头
                    return !params.BRANCH_TAG.startsWith('rel-')
                }
            }
            steps {
                script {
                    PrintMes("SonarQube Analysis", 'green')
                    sonarq.SonarQubeAnalysis("${JOB_NAME}", 'SonarqubeServ13', 'Jenkins-SonarqubeServ')
                }
            }
        }
        stage("Quality Gate") {
            when {
                expression { 
                    // 检查 BRANCH_TAG 是否不以 'rel-' 开头
                    return !params.BRANCH_TAG.startsWith('rel-')
                }
            }
            steps {
                script {
                    PrintMes("Checking Quality Gate", 'green')
                    sonarq.checkQualityGate(5)
                }
            }
        }
        stage('Wait for SonarQube Analysis') {
            when {
                expression { 
                    // 检查 BRANCH_TAG 是否不以 'rel-' 开头
                    return !params.BRANCH_TAG.startsWith('rel-')
                }
            }
            steps {
                script {
                    PrintMes("Wait for SonarQube Analysis'", 'green')
                    //sh "echo ${JOB_NAME}"
                    //sh "echo ${env.JOB_NAME}"
                    sonarq.waitForSonarQubeAnalysis('SonarqubeServ13', 'Jenkins-SonarqubeServ', "${JOB_NAME}", 10)
                }
            }
        }
    }
    post {
        always{
            script {
                println("流水线结束后，经常做的事情")
            }
        }
        success {
            script {
                println("流水线结束后，经常做的事情")
                dingtalk.DingdingReq(robotId, "构建成功 ✅")
            }
        }
        failure{
            script {
                println("流水线结束后，经常做的事情")
                dingtalk.DingdingReq(robotId, "构建失败 ❌")
            }
        }
        aborted{
            script {
                println("流水线取消后，做的事情 ")
                dingtalk.DingdingReq(robotId, "构建取消 ⚠️")
            }
        }
    }
}